<template>
    <!-- <van-pull-refresh v-model="isLoading" @refresh="onRefresh"> -->
    <div class="main_topWarp">
        <van-icon class="topWarp_back_btn" @click="goBack()" name="arrow-left" />
        <div>
            <span class="topWarp_title">{{ reportingType.shareName }}</span>
        </div>
    </div>
    <!-- 表格 -->
    <div class="DataReporting_box">
        <div class="DataReporting_content">
            <div class="DataReporting_top">
                <div class="addReport">新增填报</div>
                <div class="lookData" @click="LookDataList">查看数据</div>
            </div>
            <div class="DataReporting_main">
                <van-cell-group>
                    <van-form>
                        <van-cell v-for="(item, index)  in fieldsData" key="item.id">
                            <van-field v-if="item.fieldDBType == '文本' && item.optionFieldID == null" :label="item.name"
                                type="textarea" :placeholder="`请输入${item.name}`"
                                v-model="formData[index].FieldValue"></van-field>
                            <van-field v-if="item.fieldDBType == '文本' && item.optionFieldID !== null" :label="item.name"
                                type="textarea" :placeholder="`请选择${item.name}`" v-model="formData[index].FieldValue"
                                readonly clickable @click.stop="showOption(item.name)"></van-field>
                            <van-field v-if="item.fieldDBType == '数字'" type="number" :label="item.name"
                                :placeholder="`请输入${item.name}`" v-model="formData[index].FieldValue"
                                @input="limitToPositive($event)"></van-field>
                            <van-field v-if="item.fieldDBType == '整数'" type="digit" :label="item.name"
                                :placeholder="`请输入${item.name}`" v-model="formData[index].FieldValue"></van-field>
                            <van-field v-if="item.fieldDBType == '日期'" name="stepper" :label="item.name"
                                v-model="formData[index].FieldValue" readonly clickable placeholder="点击选择日期"
                                @click="showCalendar = true">
                            </van-field>
                            <van-field v-if="item.fieldDBType == '日期时间'" name="stepper" :label="item.name"
                                v-model="formData[index].FieldValue" readonly clickable placeholder="点击选择日期"
                                @click="showdateCalendar = true">
                            </van-field>
                            <van-field v-if="item.fieldDBType == '文件位置'" name="uploader" label-width="120"
                                input-align="right" :label="item.name">
                                <template #input v-if="item.fieldDBType == '文件位置'">
                                    <van-uploader result-type="file" max-count="1" :deletable="!detail"
                                        v-model="uploader" :before-read="beforeRead"
                                        :after-read="(file) => afterRead(file, index)" :before-delete="delImg" />
                                </template>
                            </van-field>
                            <!-- 日期 -->
                            <template v-if="item.fieldDBType == '日期' && showCalendar">
                                <van-popup v-model:show="showCalendar" round position="bottom">
                                    <van-datetime-picker cancel-button-text=""
                                        @confirm="onConfirm(currentDateYMD, index, item.fieldDBType)"
                                        @cancel="showCalendar = false" v-model="currentDateYMD" type="date"
                                        title="选择完整时间" :formatter="formatter" :min-date="minDate" />

                                </van-popup>
                            </template>
                            <!-- 日期时间 -->
                            <template v-if="item.fieldDBType == '日期时间' && showdateCalendar">
                                <van-popup v-model:show="showdateCalendar" round position="bottom">
                                    <van-datetime-picker cancel-button-text=""
                                        @confirm="onConfirm(currentDateALL, index, item.fieldDBType)"
                                        @cancel="showdateCalendar = false" v-model="currentDateALL" type="datetime"
                                        title="选择完整日期时间" :formatter="formatter" :min-date="minDate" />
                                </van-popup>
                            </template>
                            <!-- 类型-->
                            <template v-if="item.fieldDBType == '文本' && item.optionFieldID !== null && showFYType">
                                <van-popup v-model:show="showFYType" round position="bottom">
                                    <van-picker title="请选择" :columns="PickerColumns"
                                        @confirm="(value) => onPickerConfirm(value, index)" @cancel="cancelPick" />
                                </van-popup>
                            </template>
                        </van-cell>

                    </van-form>
                    <!-- 提交按钮 -->
                    <div class="my_info_loginout" @click="onSubmit">
                        <van-button block type="primary" class="btn1"> 提交 </van-button>
                    </div>
                </van-cell-group>
            </div>
        </div>
    </div>

    <!-- </van-pull-refresh> -->
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { Toast, Notify } from 'vant';
import { useStore } from "vuex"; // ⚪️ 引入状态管理
import router from "@/router";
import { useRoute } from 'vue-router';
import { ShareDataGetTableFieldsForAdd, ShareFileUpload, ShareDataSaveAddData, ShareDataGetOptionData } from "@/network/DataManagement.js";
export default {
    setup() {

        const formItems = reactive({});
        // 获取当前路由信息
        const route = useRoute();
        const state = reactive({
            isLoading: false,
            reportingType: {
                id: route.query.Id,
                type: route.query.type,
                shareName: route.query.shareName
            },
            fieldsData: [], // 后端返回的数据
            // 日期展示
            showCalendar: false,
            // 日期时间展示
            showdateCalendar: false,
            //图片上传
            flag: false, // 上传时候禁用上传按钮
            PayImg: '',
            uploader: [], // 组件默认显示图片信息
            // 下拉列表费用类型展示
            showFYType: false,
            PickerColumns: [], //下拉列表数据

        })
        // 表单生成相关
        const formData = reactive([]);
        // 日期
        const currentDateYMD = ref(new Date());
        const currentDateALL = ref(new Date());

        /*****************state**end*************************/

        // 初始化挂载
        onMounted(() => {
            getInitDataList()
            console.log('传过来的数据', state.reportingType);

        });
        // 返回上一页
        const goBack = () => {
            router.go(-1)
        }
        // 获取首页填报页列表数据
        const getInitDataList = () => {
            let params = {
                mainid: state.reportingType.id
            }
            ShareDataGetTableFieldsForAdd(params).then((res) => {
                console.log('res', res);
                state.fieldsData = res.data;
                // 动态添加属性到formData
                res.data.forEach((item, index) => {
                    //     // 在每次循环时创建一个新的对象实例
                    const formDataItem = {
                        Name: item.name,
                        // FieldValue: ''
                        // FieldValue:item.fieldDBType === '日期时间' && item.busiProperty !== null? formatTimeAll(new Date()) :item.fieldDBType === '日期' && item.busiProperty !== null? formatTimeday(new Date()): '' 
                        FieldValue: item.busiProperty !== null ? item.fieldValue : ''
                    };
                    formData.push(formDataItem); // 将新对象推入formData数组
                });

            })
        }
        // 下拉刷新
        const onRefresh = () => {
            getInitDataList()
            state.isLoading = false
        }

        /***日期选择器****/
        const formatTimeAll = (time) => {
            const datetime = new Date(time);
            const year = datetime.getFullYear();
            const month = String(datetime.getMonth() + 1).padStart(2, '0');
            const day = String(datetime.getDate()).padStart(2, '0');
            const hours = String(datetime.getHours()).padStart(2, '0');
            const minutes = String(datetime.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        const formatTimeday = (time) => {
            if (time !== null || time != undefined) {
                const datetime = new Date(time);
                const year = datetime.getFullYear();
                const month = String(datetime.getMonth() + 1).padStart(2, '0');
                const day = String(datetime.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } else {
                return null
            }

        }
        // 格式
        const formatter = (type, val) => {
            if (type === 'year') {
                return val + '年';
            }
            if (type === 'month') {
                return val + '月';
            }
            if (type === 'day') {
                return val + '日';
            }
            return val;
        };

        // 日期选择确认
        const onConfirm = (date, index, type) => {
            switch (type) {
                case '日期':
                    formData[index].FieldValue = formatTimeday(date);
                    state.showCalendar = false;
                    break;
                case '日期时间':
                    formData[index].FieldValue = formatTimeAll(date);
                    state.showdateCalendar = false;
                    break;

                default:
                    break;
            }
            console.log('date:', formatTimeAll(date), index);

        };
        /***文件上传****/
        const delImg = (file, detail) => {
            state.PayImg = ''; // 只有一张直接清空数组
            return true
        }
        // 上传图片前返回布尔值
        const beforeRead = (file) => {
            if (
                file.type !== "image/png" &&
                file.type !== "image/jpeg" &&
                file.type !== "image/jpg"
            ) {

                this.$toast.fail("请上传 png,jpg格式图片");
                return false;
            }
            return true;
        }
        const afterRead = (file, index) => {
            state.flag = true;
            file.status = "uploading";
            file.message = "上传中...";
            let fileData = new FormData(); // 上传图片要formData类型
            fileData.append("uploadImage", file.file);
            ShareFileUpload(fileData).then((response) => {
                console.log('response', response);
                console.log('file', file);
                if (response.success) {
                    file.status = "done";
                    file.message = "上传完成";
                    state.flag = false;
                    state.PayImg = response.Data; // 因为只有一张，直接传1个字符串
                    formData[index].FieldValue = response.message
                } else {
                    file.status = "failed";
                    file.message = "上传失败";
                }
            });
        }
        // 限制输入为正数的处理函数
        const limitToPositive = (event) => {
            const inputValue = parseFloat(event.target.value);
            if (isNaN(inputValue) || inputValue < 0) {
                // 如果输入不是数字或小于0，则重置为0
                event.target.value = '';
                formData.value[index].FieldValue = 0; // 根据需要调整这里的逻辑，也可以选择不赋值或赋值为null等
            } else {
                formData.value[index].FieldValue = inputValue;
            }
        };



        /***提交新增数据****/
        const onSubmit = (value) => {
            let params = {
                mainid: state.reportingType.id,
                data: formData
            }
            ShareDataSaveAddData(params).then((res) => {
                console.log('res', res);
                if (res.success) {
                    Notify({
                        type: 'success',
                        message: '新增成功'
                    });
                    LookDataList()
                } else {
                    Notify({
                        type: 'danger',
                        message: res.message
                    });
                }
            })
        };
        // 跳转到数据管理页面
        const LookDataList = () => {
            router.push({
                name: 'DataManaging',
                query: {
                    // 传递参数到DataManaging页面
                    Id: state.reportingType.id,
                    shareName: state.reportingType.shareName
                }
            });
        }

        // 打开弹窗
        const showOption = (field) => {
            let fieldId = ''
            let mainid = state.reportingType.id
            state.fieldsData.forEach(item => {
                if (item.name == field) {
                    fieldId = item.id
                }
            });

            state.showFYType = true
            GetOptionData(fieldId, mainid)
        }
        // 取消打开下拉列表
        const cancelPick = () => {
            state.showFYType = false
        }
        // 弹框确认选择
        const onPickerConfirm = (value, index) => {
            formData[index].FieldValue = value.value;
            state.showFYType = false;
        };
        // 获取下拉列表的值
        const GetOptionData = (fieldId, mainid) => {
            let params = {
                ID: fieldId || "",		//字段的ID
                ShareMainID: mainid || "", //分享ID”，
                PageIndex: 1,//页码， 从1开始
                PageSize: 10,//每页大小
                DependencyValue: '' //依赖源字段的值
            }
            ShareDataGetOptionData(params).then((res) => {
                console.log('res', res.data);
                state.PickerColumns = res.data.map(item => {
                    let key = Object.keys(item)[0];
                    return {
                        text: item[key],
                        value: item[key],
                    };
                });

            })
        }


        return {
            ...toRefs(state),
            onRefresh,
            goBack,
            formData,
            onSubmit, formItems,
            onConfirm,
            // 日期
            currentDateYMD,
            currentDateALL,
            minDate: new Date(2024, 0, 1),
            formatter,
            // 文件上传
            delImg,
            beforeRead,
            afterRead,
            // 跳转页面
            LookDataList,
            limitToPositive,
            cancelPick, onPickerConfirm, GetOptionData, showOption


        };
    },
};
</script>

<style scoped></style>